<template>
  <Layout>
    <div class="role-container">
      <!-- 顶部操作区 -->
      <div class="action-bar">
        <el-button type="primary" @click="handleCreateRole">
          新建角色
        </el-button>
        <el-button type="primary" @click="addPredefinedRoles">
          批量添加预定义角色
        </el-button>
      </div>

      <!-- 角色列表 -->
      <el-card class="table-card">
        <el-table
          v-loading="loading"
          :data="roleList"
          style="width: 100%"
          border
        >
          <el-table-column prop="name" label="角色编码" min-width="180" />
          <el-table-column label="角色名称" min-width="180">
            <template #default="scope">
              {{ scope.row.displayName || scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column prop="description" label="角色描述" min-width="250" />
          <el-table-column prop="userCount" label="员工数" width="120" align="center" />
          <el-table-column label="操作" width="180" align="center">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="handleViewRole(scope.row)"
              >
                查看
              </el-button>
              <el-button
                type="primary"
                link
                @click="handleEditRole(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                link
                @click="handleDeleteRole(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>

      <!-- 角色表单弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEdit ? '编辑角色' : '新建角色'"
        width="600px"
        destroy-on-close
      >
        <el-form
          ref="roleFormRef"
          :model="roleForm"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色编码" prop="name">
            <el-input v-model="roleForm.name" placeholder="请输入角色编码（字母、数字和下划线）" />
            <div class="hint-text">角色编码只能包含字母、数字和下划线</div>
          </el-form-item>
          <el-form-item label="角色名称" prop="displayName">
            <el-input v-model="roleForm.displayName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input
              v-model="roleForm.description"
              type="textarea"
              placeholder="请输入角色描述"
              :rows="3"
            />
          </el-form-item>
          <el-form-item label="权限设置">
            <el-tree
              ref="permissionTreeRef"
              :data="permissionOptions"
              show-checkbox
              node-key="id"
              :default-checked-keys="selectedPermissions"
              :props="{ label: 'label', children: 'children' }"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getRoleList, createRole, updateRole, deleteRole } from '../../api/role';
import Layout from '../../components/Layout.vue';

// 权限数据
const permissionOptions = [
  {
    id: '1',
    label: '所有权限',
    children: [
      {
        id: '1-1',
        label: '客户管理',
        children: [
          { id: '1-1-1', label: '查看客户' },
          { id: '1-1-2', label: '编辑客户' },
        ]
      },
      {
        id: '1-2',
        label: '订单管理',
        children: [
          { id: '1-2-1', label: '查看订单' },
          { id: '1-2-2', label: '修改订单' },
        ]
      },
      {
        id: '1-3',
        label: '商品管理',
        children: [
          { id: '1-3-1', label: '查看商品' },
          { id: '1-3-2', label: '编辑商品' },
        ]
      },
      {
        id: '1-4',
        label: '营销管理',
        children: [
          { id: '1-4-1', label: '营销模块' },
          { id: '1-4-2', label: '客户模块' },
        ]
      },
      {
        id: '1-5',
        label: '财务管理',
        children: [
          { id: '1-5-1', label: '财务模块' },
          { id: '1-5-2', label: '查看订单' },
        ]
      },
      {
        id: '1-6',
        label: '内容模块',
        children: [
          { id: '1-6-1', label: '内容模块' }
        ]
      },
      {
        id: '1-7',
        label: '美工',
        children: [
          { id: '1-7-1', label: '内容模块' }
        ]
      }
    ]
  }
];

// 列表数据
const loading = ref(false);
const roleList = ref<any[]>([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 表单相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const roleFormRef = ref<FormInstance>();
const permissionTreeRef = ref();
const selectedPermissions = ref<string[]>([]);

const roleForm = reactive({
  objectId: '',
  name: '',
  displayName: '',
  description: '',
  permissions: [] as string[]
});

// 表单验证规则
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '角色编码只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  displayName: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 30, message: '长度在 2 到 30 个字符之间', trigger: 'blur' }
  ],
  description: [
    { required: false, message: '请输入角色描述', trigger: 'blur' },
    { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
  ]
});

// 预定义的角色列表
const predefinedRoles = [
  {
    name: 'super_admin',
    displayName: '超级管理员',
    description: '拥有系统所有权限',
    permissions: {
      system: { view: true, add: true, edit: true, delete: true },
      product: { view: true, add: true, edit: true, delete: true },
      order: { view: true, add: true, edit: true, delete: true },
      customer: { view: true, add: true, edit: true, delete: true },
      marketing: { view: true, add: true, edit: true, delete: true },
      content: { view: true, add: true, edit: true, delete: true },
      finance: { view: true, add: true, edit: true, delete: true },
      data: { view: true, add: true, edit: true, delete: true }
    }
  },
  {
    name: 'product_admin',
    displayName: '商品管理员',
    description: '负责管理商品相关信息',
    permissions: {
      system: { view: false, add: false, edit: false, delete: false },
      product: { view: true, add: true, edit: true, delete: true },
      order: { view: true, add: false, edit: false, delete: false },
      customer: { view: false, add: false, edit: false, delete: false },
      marketing: { view: false, add: false, edit: false, delete: false },
      content: { view: false, add: false, edit: false, delete: false },
      finance: { view: false, add: false, edit: false, delete: false },
      data: { view: false, add: false, edit: false, delete: false }
    }
  },
  {
    name: 'order_admin',
    displayName: '订单管理员',
    description: '负责管理订单相关信息',
    permissions: {
      system: { view: false, add: false, edit: false, delete: false },
      product: { view: true, add: false, edit: false, delete: false },
      order: { view: true, add: true, edit: true, delete: true },
      customer: { view: true, add: false, edit: false, delete: false },
      marketing: { view: false, add: false, edit: false, delete: false },
      content: { view: false, add: false, edit: false, delete: false },
      finance: { view: false, add: false, edit: false, delete: false },
      data: { view: false, add: false, edit: false, delete: false }
    }
  },
  {
    name: 'customer_service',
    displayName: '客服专员',
    description: '负责客户服务和处理客户问题',
    permissions: {
      system: { view: false, add: false, edit: false, delete: false },
      product: { view: true, add: false, edit: false, delete: false },
      order: { view: true, add: false, edit: true, delete: false },
      customer: { view: true, add: true, edit: true, delete: false },
      marketing: { view: false, add: false, edit: false, delete: false },
      content: { view: false, add: false, edit: false, delete: false },
      finance: { view: false, add: false, edit: false, delete: false },
      data: { view: false, add: false, edit: false, delete: false }
    }
  },
  {
    name: 'marketing_specialist',
    displayName: '营销专员',
    description: '负责营销活动策划和执行',
    permissions: {
      system: { view: false, add: false, edit: false, delete: false },
      product: { view: true, add: false, edit: false, delete: false },
      order: { view: false, add: false, edit: false, delete: false },
      customer: { view: true, add: false, edit: false, delete: false },
      marketing: { view: true, add: true, edit: true, delete: true },
      content: { view: true, add: true, edit: true, delete: true },
      finance: { view: false, add: false, edit: false, delete: false },
      data: { view: true, add: false, edit: false, delete: false }
    }
  }
];

// 获取角色列表
const fetchRoleList = async () => {
  loading.value = true;
  try {
    // 构建查询参数
    const params = {
      limit: pageSize.value,
      skip: (currentPage.value - 1) * pageSize.value,
      count: 1
    };
    
    const res: any = await getRoleList(params);
    roleList.value = res.results.map((item: any) => ({
      ...item,
      userCount: item.users ? item.users.length : 0
    }));
    total.value = res.count;
  } catch (error) {
    console.error('获取角色列表失败:', error);
    ElMessage.error('获取角色列表失败');
  } finally {
    loading.value = false;
  }
};

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchRoleList();
};

const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  fetchRoleList();
};

// 新建角色
const handleCreateRole = () => {
  isEdit.value = false;
  roleForm.objectId = '';
  roleForm.name = '';
  roleForm.displayName = '';
  roleForm.description = '';
  roleForm.permissions = [];
  selectedPermissions.value = [];
  dialogVisible.value = true;
};

// 查看角色
const handleViewRole = (row: any) => {
  isEdit.value = true;
  roleForm.objectId = row.objectId;
  roleForm.name = row.name;
  roleForm.displayName = row.displayName || row.name;
  roleForm.description = row.description || '';
  roleForm.permissions = row.permissions || [];
  selectedPermissions.value = row.permissions || [];
  dialogVisible.value = true;
  
  // 设置表单为只读
  setTimeout(() => {
    const inputs = document.querySelectorAll('.el-input__inner');
    inputs.forEach((input: any) => {
      input.setAttribute('readonly', 'readonly');
    });
    const textarea = document.querySelectorAll('.el-textarea__inner');
    textarea.forEach((input: any) => {
      input.setAttribute('readonly', 'readonly');
    });
    
    // 禁用树形控件选择
    permissionTreeRef.value.setCheckedKeys(selectedPermissions.value);
    permissionTreeRef.value.disabled = true;
  }, 0);
};

// 编辑角色
const handleEditRole = (row: any) => {
  isEdit.value = true;
  roleForm.objectId = row.objectId;
  roleForm.name = row.name;
  roleForm.displayName = row.displayName || row.name;
  roleForm.description = row.description || '';
  roleForm.permissions = row.permissions || [];
  selectedPermissions.value = row.permissions || [];
  dialogVisible.value = true;
};

// 删除角色
const handleDeleteRole = (row: any) => {
  ElMessageBox.confirm(
    '确定要删除该角色吗？删除后不可恢复！',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteRole(row.objectId);
      ElMessage.success('删除成功');
      fetchRoleList();
    } catch (error) {
      console.error('删除角色失败:', error);
      ElMessage.error('删除角色失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 提交表单
const submitForm = async () => {
  if (!roleFormRef.value) return;
  
  await roleFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 获取选中的权限
        const checkedKeys = permissionTreeRef.value.getCheckedKeys();
        const halfCheckedKeys = permissionTreeRef.value.getHalfCheckedKeys();
        roleForm.permissions = [...checkedKeys, ...halfCheckedKeys];
        
        if (isEdit.value) {
          // 编辑角色
          await updateRole(roleForm.objectId, {
            name: roleForm.name,
            displayName: roleForm.displayName,
            description: roleForm.description,
            permissions: roleForm.permissions
          });
          ElMessage.success('更新成功');
        } else {
          // 创建角色
          await createRole({
            name: roleForm.name,
            displayName: roleForm.displayName,
            description: roleForm.description,
            permissions: roleForm.permissions,
            users: []
          });
          ElMessage.success('创建成功');
        }
        
        dialogVisible.value = false;
        fetchRoleList();
      } catch (error) {
        console.error('保存角色失败:', error);
        ElMessage.error('保存角色失败');
      }
    }
  });
};

// 批量添加预定义角色
const addPredefinedRoles = async () => {
  try {
    loading.value = true;
    // 逐个添加角色
    for (const role of predefinedRoles) {
      await createRole(role);
    }
    ElMessage.success('预设角色添加成功');
    fetchRoleList(); // 刷新列表
  } catch (error: any) {
    console.error('添加预设角色失败:', error);
    ElMessage.error(error.response?.data?.error || '添加预设角色失败');
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchRoleList();
});
</script>

<style scoped>
.role-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  margin-top: 20px;
}
</style> 